package com.algo.pattern.observable.observable;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StockUpdateObserverManager {

    private static final StockUpdateObserverManager INSTANCE = new StockUpdateObserverManager();

    private StockUpdateObserverManager() {}

    public static StockUpdateObserverManager getInstance() {
        return INSTANCE;
    }

    /**
     * 观察者
     */
    private StockUpdateObserver observer = new StockUpdateObserver();

    private Map<String, StockUpdateObservable> observableMap = new ConcurrentHashMap<>();

    /**
     * 监听消息
     * @param messageId
     */
    public void observer(String messageId) {
        StockUpdateObservable observable = new StockUpdateObservable();
        observable.addObserver(observer);
        System.out.println("添加监听成功，messageId：" + messageId);

        observableMap.put(messageId, observable);
    }

    /**
     * 调度中心处理后，通知到库存中心
     * @param messageId
     * @param updateResult
     */
    public void inform(String messageId, boolean updateResult) {
        System.out.println("调度中心处理结束，通知到库存中心，messageId：" + messageId + ", updateResult：" + updateResult);
        StockUpdateObservable observable = observableMap.get(messageId);
        observable.setResult(updateResult);

        observableMap.remove(messageId);
    }

}
